﻿using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using SkiaSharp;
using System.Xml.Linq;
using Yz.Core.Extensions;

namespace Yz.FileService.Tools
{
    public class YzWord
    {

        public static string ToHtml(string filePath)
        {
            byte[] array = File.ReadAllBytes(filePath);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(array, 0, array.Length);
                WordprocessingDocument val = WordprocessingDocument.Open((Stream)memoryStream, true);
                try
                {
                    return ConvertToHtml(val);
                }
                finally
                {
                    ((IDisposable)val)?.Dispose();
                }
            }
        }
        private static string ConvertToHtml(WordprocessingDocument wDoc)
        {
            int imageCounter = 0;
            string pageTitle = "";
            CoreFilePropertiesPart coreFilePropertiesPart = wDoc.CoreFilePropertiesPart;
            if (coreFilePropertiesPart != null)
            {
                pageTitle = ((string)PtOpenXmlExtensions.GetXDocument(coreFilePropertiesPart).Descendants(DC.title).FirstOrDefault()) ?? "";
            }
            if (pageTitle.IsEmpty())
            {
                pageTitle = "Word预览";
            }
            WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
            {
                AdditionalCss = "body {  max-width: 100%; padding: 0;background-color:#404040 }",
                PageTitle = pageTitle,
                FabricateCssClasses = true,
                CssClassPrefix = "pt-",
                RestrictToSupportedLanguages = false,
                RestrictToSupportedNumberingFormats = false,
                GeneralCss = "span { white-space: pre-wrap; } div{margin: 0 auto; max-width: 832px; padding: 0 80px;background-color:#fff;width:832px}  p{text-indent:0 !important}"
            };

            settings.ImageHandler = delegate (OpenXmlPowerTools.ImageInfo imageInfo)
            {
                int num = ++imageCounter;
                string a = imageInfo.ContentType.Split('/')[1].ToLower();
                SKEncodedImageFormat imageFormat = SKEncodedImageFormat.Avif;
                if (a == "png")
                {
                    imageFormat = SKEncodedImageFormat.Png;
                }
                else if (a == "gif")
                {
                    imageFormat = SKEncodedImageFormat.Gif;
                }
                else if (a == "bmp")
                {
                    imageFormat = SKEncodedImageFormat.Bmp;
                }
                else if (a == "jpeg" || a == "jpg")
                {
                    imageFormat = SKEncodedImageFormat.Jpeg;
                }
                else if (a == "tiff")
                {
                    a = "gif";
                    imageFormat = SKEncodedImageFormat.Gif;
                }
                else if (a == "webp")
                {
                    a = "webp";
                    imageFormat = SKEncodedImageFormat.Webp;
                }
                if (imageFormat == SKEncodedImageFormat.Avif)
                {
                    return null;
                }
                string arg = null;
                try
                {
                    byte[] inArray = null;
                    using (MemoryStream memStream = new MemoryStream())
                    using (SKManagedWStream wstream = new SKManagedWStream(memStream))
                    {
                        imageInfo.SKBitmap.Encode(wstream, imageFormat, 100);
                        inArray = memStream.ToArray();

                    }
                    arg = Convert.ToBase64String(inArray);
                }
                catch (Exception)
                {
                    return null;
                }

                string mimeType = imageInfo.ContentType;
                string value = $"data:{mimeType};base64,{arg}";
                return new XElement(Xhtml.img, new XAttribute(NoNamespace.src, value), imageInfo.ImgStyleAttribute, (imageInfo.AltText != null) ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
            };
            XElement xElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
            XDocument xDocument = new XDocument(new XDocumentType("html", null, null, null), xElement);
            return xDocument.ToString(SaveOptions.DisableFormatting);
        }
    }
}
